import 'dart:async';

import 'package:flutter/material.dart';
import 'package:lite_message/widgets/lm_button.dart';

import 'package:lite_message/util/app_util.dart';

///倒计时
class CountDownBtn extends StatefulWidget {
  ///持续时间
  final int duration;

  ///点击事件
  final Future<bool> Function() onTap;

  ///默认文本
  final String defaultText;

  const CountDownBtn({
    Key key,
    this.duration = 60,
    @required this.onTap,
    this.defaultText = '发送验证码',
  }) : super(key: key);
  @override
  _CountDownBtnState createState() => _CountDownBtnState();
}

class _CountDownBtnState extends State<CountDownBtn> {
  ///显示的文字
  String _showText;

  ///持续时间
  int _duration;

  ///计时器
  Timer _timer;

  @override
  void setState(fn) {
    if (this.mounted) super.setState(fn);
  }

  @override
  void initState() {
    super.initState();
    _showText = widget.defaultText;
    _duration = widget.duration;
    setState(() {});
  }

  @override
  void dispose() {
    _timer?.cancel();
    _timer = null;
    super.dispose();
  }

  ///开始倒计时
  _start() async {
    if (widget.onTap != null) {
      ///是否发送成功
      final bool _success = await widget.onTap();

      if (_success) {
        _duration--;

        _showText = '${_duration.toString().padLeft(2, '0')}s';

        setState(() {});

        _timer = Timer.periodic(const Duration(seconds: 1), (t) {
          _duration--;

          _showText = '${_duration.toString().padLeft(2, '0')}s';

          if (_duration == 0) {
            _timer?.cancel();

            _timer = null;

            _showText = '重新发送';

            _duration = widget.duration;
          }

          setState(() {});
        });
      }
    }
  }

  @override
  Widget build(BuildContext context) {
    return LmButton(
      text: '$_showText',
      width: 260.px,
      height: 90.px,
      radius: 20.px,
      color: Theme.of(context).accentColor,
      onPressed: _duration == widget.duration && widget.onTap != null
          ? () async {
              await _start();
            }
          : null,
      style: TextStyle(
        fontSize: 30.sp,
        color: Theme.of(context).bottomAppBarColor,
        fontWeight: FontWeight.bold,
      ),
    );
  }
}
